package com.glsc.ngateway.platform.service.dev;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.useragent.Platform;
import com.alibaba.fastjson.JSONObject;
import com.glsc.ngateway.common.api.common.enums.Constant;
import com.glsc.ngateway.common.api.common.enums.DictConstant;
import com.glsc.ngateway.common.api.common.enums.PlatformConstant;
import com.glsc.ngateway.common.api.common.utils.PageUtil;
import com.glsc.ngateway.common.api.flowable.dto.*;
import com.glsc.ngateway.common.api.flowable.dto.param.ParamCreateDto;
import com.glsc.ngateway.common.api.flowable.dto.param.ParamDeleteDto;
import com.glsc.ngateway.common.api.flowable.dto.param.ParamDoTaskDto;
import com.glsc.ngateway.common.api.flowable.dto.param.ParamRollbackDto;
import com.glsc.ngateway.common.api.flowable.dto.task.config.ProcessEditConfigDto;
import com.glsc.ngateway.common.api.flowable.feign.IFeignFlowableService;
import com.glsc.ngateway.common.api.flowable.resp.*;
import com.glsc.ngateway.common.api.ldap.dto.LdapEhrEmpDto;
import com.glsc.ngateway.common.api.ldap.feign.IFeignLdapService;
import com.glsc.ngateway.common.api.platform.dto.user.PlatformUserDto;
import com.glsc.ngateway.common.api.platform.dto.user.UserLeadersDto;
import com.glsc.ngateway.common.api.shortmsg.bo.MessageGenericVo;
import com.glsc.ngateway.common.api.shortmsg.feign.IFeignShortmsgService;
import com.glsc.ngateway.common.base.domain.mysql.gateway.other.SystemConfig;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.Appendix;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.User;
import com.glsc.ngateway.common.base.domain.mysql.gateway.system.VEhrAdminStaff;
import com.glsc.ngateway.common.base.exception.PlatformException;
import com.glsc.ngateway.common.base.repo.mysql.gateway.platform.AppendixRepo;
import com.glsc.ngateway.common.base.repo.mysql.gateway.platform.FlowEventUnionImporveRepo;
import com.glsc.ngateway.common.base.repo.mysql.gateway.platform.system.VEhrAdminStaffRepository;
import com.glsc.ngateway.platform.aspect.UserCache;
import com.glsc.ngateway.platform.domain.*;
//import com.glsc.ngateway.platform.dto.FlowFormTestTaskDto;
import com.glsc.ngateway.platform.dto.FlowParamDevManageSearchDto;
import com.glsc.ngateway.platform.dto.ResponseSituationDevManageDto;
import com.glsc.ngateway.platform.repo.DevManageRepository;
import com.glsc.ngateway.platform.repo.DevMemberRepository;
import com.glsc.ngateway.platform.repo.DevTaskChangeLogRepository;
import com.glsc.ngateway.platform.repo.DevTaskDetailRepository;
import com.glsc.ngateway.platform.service.*;
import com.glsc.ngateway.platform.service.gitee.GiteeNewService;
import com.glsc.ngateway.platform.service.it.DictionaryService;
import com.glsc.ngateway.platform.service.itflow.config.ProcessEditConfigService;
import com.glsc.ngateway.platform.service.system.SystemMainService;
import com.glsc.ngateway.platform.service.system.SystemMemberService;
import com.glsc.ngateway.platform.utils.DateUtils;
import com.glsc.ngateway.platform.utils.JsonTool;
import com.glsc.ngateway.platform.utils.PlatformLocalConstant;
import com.google.common.collect.ImmutableList;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import com.glsc.ngateway.common.base.domain.mysql.gateway.system.SystemMain;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import javax.validation.constraints.NotNull;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static com.glsc.ngateway.common.api.common.enums.DictConstant.NO_CLOSE;
import static com.glsc.ngateway.common.api.common.enums.PlatformConstant.*;
import static com.glsc.ngateway.platform.utils.DateUtils.getCurrentDate;
import static com.glsc.ngateway.platform.utils.PlatformLocalConstant.IS_CLOSE;

/**
 * @author weizt
 * @date 2024/07/11
 * 事件管理流程服务类，
 */
@Service
public class DevManageService {

    Logger logger = LoggerFactory.getLogger(DevManageService.class);

    @Resource
    private DevManageRepository devManageRepository;

    @Resource
    private DevTaskChangeLogRepository devTaskChangeLogRepository;

    @Resource
    private DevTaskDetailRepository devTaskDetailRepository;

    @Resource
    private DevMemberRepository devMemberRepository;

    @Resource
    private FlowEventUnionImporveRepo flowEventUnionImporveRepo;

    @Resource
    private GiteeNewService giteeNewService;

    @Resource
    private AppendixRepo appendixRepo;

    @Resource
    @Qualifier("transactionManagerMysql")
    private PlatformTransactionManager transactionManager;

    @Resource
    private UserCache userCache;

    @Resource
    private IFeignFlowableService feignFlowableService;

    @Resource
    private FlowCommonService flowCommonService;

    @Resource
    private EventImproveService eventImproveService;

    @Resource
    private ProcessEditConfigService processEditConfigService;

    @Resource
    private SystemConfigService systemConfigService;

    @Resource
    private UserService userService;

    @Resource
    private IFeignLdapService iFeignLdapService;

    @Resource
    private MailService mailService;

    @Resource
    private SystemMemberService systemMemberService;

    @Resource
    private SystemMainService systemMainService;

    @Autowired
    private DictionaryService dictionaryService;

    @Resource
    private IFeignShortmsgService iFeignShortmsgService;

    @Resource
    private TestTaskService testTaskService;

    @Value("${wechat.url}")
    private String weChatUrl;

    @Resource
    private VEhrAdminStaffRepository vEhrAdminStaffRepository;

    public List<FlowFormDevManage> queryAllByNODelAndNOCloase(String systemCode) {
        List<String> nodeNames = ImmutableList.of("等待上线");
        return devManageRepository.queryAllByIsCloseAndIsDeleteAndSystemCodeAndCurrentNodeInOrderByInsertTimeDesc(DictConstant.NO_CLOSE,DictConstant.NO_DELETE,systemCode,nodeNames);
    }

    public List<FlowFormDevManage> findAllDemands() {
        return devManageRepository.findAllByIsDelete(DictConstant.NO_DELETE);
    }

    /**
     * 根据processId获取事件管理流程表单
     *
     * @param processId 流程iD
     * @return
     */
    public FlowFormDevManage findFormByProcessId(String processId) {
        FlowFormDevManage flowFormDevManage = devManageRepository.findByProcessId(processId);
        if (flowFormDevManage != null) {
            //填充系统名称
            if (StrUtil.isNotEmpty(flowFormDevManage.getSystemCode())) {
                Map<String, String> operationMap = systemMainService.queryAll().stream().filter(e -> StrUtil.isNotEmpty(e.getSystemClassNo())).collect(Collectors.toMap(SystemMain::getSystemClassNo, SystemMain::getOpName));
                flowFormDevManage.setSystemName(operationMap.get(flowFormDevManage.getSystemCode()));
            }
            //填充管理员名称
            if (StrUtil.isNotEmpty(flowFormDevManage.getSystemAdminAccount())){
                LdapEhrEmpDto empDto = userService.getUserFromEhr(flowFormDevManage.getSystemAdminAccount());
                if (empDto != null){
                    flowFormDevManage.setSystemAdminName(empDto.getName());
                }
            }
        }
        //填充oa评审人员和设计人员列表中文
        List<FlowFormDevMember> devMembers = devMemberRepository.findAllByRelateIdAndDeleted(processId,DictConstant.NO_DELETE);
        if (flowFormDevManage != null && CollectionUtil.isNotEmpty(devMembers)){
            List<String> oaOkList = devMembers.stream().filter(e->e.getMemberType().equals(IT_DEV_MANAGE_MEMBER_DEMAND_OK)).map(FlowFormDevMember::getMemberAccount).collect(Collectors.toList());
            List<String> designList = devMembers.stream().filter(e->e.getMemberType().equals(IT_DEV_MANAGE_MEMBER_DESIGN)).map(FlowFormDevMember::getMemberAccount).collect(Collectors.toList());
            flowFormDevManage.setDemandOkAccountList(oaOkList);
            flowFormDevManage.setDemandDesignAccountList(designList);
        }
        //TODO 加载附件信息
        if (flowFormDevManage != null && StrUtil.isNotBlank(flowFormDevManage.getDemandDocIdList())) {
            String[] docIds = flowFormDevManage.getDemandDocIdList().split(",");
            List<Appendix> docList = new ArrayList<>();
            if (docIds != null && docIds.length > 0) {
                for (String docId : docIds) {
                    Appendix appendix = appendixRepo.findById(docId);
                    docList.add(appendix);
                }
            }
            flowFormDevManage.setDemandDocList(docList);
        }
        if (flowFormDevManage != null && StrUtil.isNotBlank(flowFormDevManage.getDemandDesignDocIdList())) {
            String[] docIds = flowFormDevManage.getDemandDesignDocIdList().split(",");
            List<Appendix> docList = new ArrayList<>();
            if (docIds != null && docIds.length > 0) {
                for (String docId : docIds) {
                    Appendix appendix = appendixRepo.findById(docId);
                    docList.add(appendix);
                }
            }
            flowFormDevManage.setDemandDesignDocList(docList);
        }
        if (flowFormDevManage != null && StrUtil.isNotBlank(flowFormDevManage.getDemandTestInstanceDocIdList())) {
            String[] docIds = flowFormDevManage.getDemandTestInstanceDocIdList().split(",");
            List<Appendix> docList = new ArrayList<>();
            if (docIds != null && docIds.length > 0) {
                for (String docId : docIds) {
                    Appendix appendix = appendixRepo.findById(docId);
                    docList.add(appendix);
                }
            }
            flowFormDevManage.setDemandTestInstanceDocList(docList);
        }
        if (flowFormDevManage != null && StrUtil.isNotBlank(flowFormDevManage.getDemandTestReportDocIdList())) {
            String[] docIds = flowFormDevManage.getDemandTestReportDocIdList().split(",");
            List<Appendix> docList = new ArrayList<>();
            if (docIds != null && docIds.length > 0) {
                for (String docId : docIds) {
                    Appendix appendix = appendixRepo.findById(docId);
                    docList.add(appendix);
                }
            }
            flowFormDevManage.setDemandTestReportDocList(docList);
        }
//        if (flowFormDevManage != null && StrUtil.isNotBlank(flowFormDevManage.getDemandOnlineDocIdList())) {
//            String[] docIds = flowFormDevManage.getDemandOnlineDocIdList().split(",");
//            List<Appendix> docList = new ArrayList<>();
//            if (docIds != null && docIds.length > 0) {
//                for (String docId : docIds) {
//                    Appendix appendix = appendixRepo.findById(docId);
//                    docList.add(appendix);
//                }
//            }
//            flowFormDevManage.setDemandOnlineDocList(docList);
//        }
//        if (flowFormDevManage != null && StrUtil.isNotBlank(flowFormDevManage.getSonarDocIdList())) {
//            String[] docIds = flowFormDevManage.getSonarDocIdList().split(",");
//            List<Appendix> docList = new ArrayList<>();
//            if (docIds != null && docIds.length > 0) {
//                for (String docId : docIds) {
//                    Appendix appendix = appendixRepo.findById(docId);
//                    docList.add(appendix);
//                }
//            }
//            flowFormDevManage.setSonarDocList(docList);
//        }
        return flowFormDevManage;
    }


    /**
     * 创建流程
     *
     * @param devManageDto 流程创建发起对象
     * @return
     */
    public FlowDoTaskRespDto createFlow(DevManageDto devManageDto, String operatorStart) {
        if (ObjectUtil.isNull(devManageDto)
                || ObjectUtil.isNull(devManageDto.getFlowableFormData())
                || StrUtil.isEmpty(operatorStart)) {
            throw PlatformException.errorWithOutMail("流程创建必填要素不能为空");
        }
        FlowFormDevManage flowableForm = devManageDto.getFlowableFormData();

        PlatformUserDto createUser = userCache.get(operatorStart);
        devManageDto.getFlowableFormData().setFlowCreatorDepartment(createUser.getDepartment());
        //【流程节点】，发起时动态指定节点处理人，
        Map<String, String> taskAssignee = new HashMap<>();
        if (StrUtil.isNotEmpty(flowableForm.getSystemAdminAccount())){
            //保存流程部门，为系统负责人所在部门
            PlatformUserDto user = userService.getUsrUrls(flowableForm.getSystemAdminAccount());
            flowableForm.setSystemBelongDepartment(user.getDepartment());
            taskAssignee = initTaskUserGroup(operatorStart,devManageDto);
        }
        //【流程节点变量】
        Map<String, String> conditionalVariable = new HashMap<>();
        //是否内部需求
//        if (StrUtil.equals(devManageDto.getFlowableFormData().getDemandInner(),DictConstant.NO)){
//            conditionalVariable.put("inner_demand","0");
//        }else {
//            conditionalVariable.put("inner_demand","1");
//        if (StrUtil.isNotEmpty(flowableForm.getSystemAdminAccount())){
//            PlatformUserDto staff = new PlatformUserDto();
//            staff.setUsername(flowableForm.getSystemAdminAccount());
//            UserLeadersDto leader = userService.getDirectLeaderAndPrimaryDepartmentLeader(staff);
//            if (leader.getAllLeaders().stream().anyMatch(e->e.equalsIgnoreCase(flowableForm.getSystemAdminAccount()))){
//                //如果系统管理员就是二级部门领导，则自己审批
//                taskAssignee.put("innerLeaderGroup",flowableForm.getSystemAdminAccount());
//            } else {
//                taskAssignee.put("innerLeaderGroup",leader.getDirectLeaders().stream().collect(Collectors.joining(",")));
//            }
//        }


//        }


        TransactionStatus status = null;
        FlowDoTaskRespDto createFlowResponse = null;
//        FlowFormDevManage flowableForm = devManageDto.getFlowableFormData();
        int flowException = 0;
        try {
            // 事务定义
            DefaultTransactionDefinition def = new DefaultTransactionDefinition();
            // 每次都开启一个新事务
            def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
            // 获取事务状态
            status = transactionManager.getTransaction(def);

            //2.表单内容（发起流程，表单内容为辅助）
            FlowStartupFormDto formDto = new FlowStartupFormDto();
            formDto.setTitle(flowableForm.getProcessTitle());
            formDto.setComment("xx");//发起备注
            formDto.setCreatorId(createUser.getUserid());
            formDto.setCreatorName(createUser.getUsername());


            ParamCreateDto paramCreateDto = new ParamCreateDto();
            paramCreateDto.setSysid(PlatformConstant.SYS_ID_GATEWAY);
            paramCreateDto.setProcessDefinitionKey(PlatformConstant.IT_DEV_MANAGE_FLOW);
            paramCreateDto.setUserid(operatorStart);//【重要！】这字段标识发起人！！！
            paramCreateDto.setContent(JSONObject.toJSON(formDto).toString());//纯粹为了flowable创建content需要一个JSON表单数据
            paramCreateDto.setTaskAssignee(taskAssignee);//各节点处理人
            paramCreateDto.setConditionalVariable(conditionalVariable);//控制流程节点变量
            paramCreateDto.setCreateComment(devManageDto.getCommentDto().getFullMessage());
            //未启流程保存草稿时，CreateToTaskDefinitionKey变量为"beginTask"，流程引擎会在创建后调到初始节点
            if (StrUtil.isNotBlank(devManageDto.getCreateToTaskDefinitionKey())) {
                paramCreateDto.setCreateToTaskDefinitionKey(devManageDto.getCreateToTaskDefinitionKey());
            }

            createFlowResponse = new FlowDoTaskRespDto();
            //4.创建flowable流程
            FlowableResponse<ResponseCreateDto> createFlowableFlowResponse = feignFlowableService.create(paramCreateDto);
            if (createFlowableFlowResponse.getStatus() == 0) {
                createFlowResponse.setProcessId(createFlowableFlowResponse.getData().getProcessId());
                logger.info("流程关联，{}", createFlowResponse);
            } else {
                String errMsg = String.format("流程创建失败，{%s}，错误码={%s}-，原因：{%s}",
                        flowableForm.getProcessTitle()
                        , createFlowableFlowResponse.getStatus(), createFlowableFlowResponse.getMsg());
                logger.error(errMsg);
                throw PlatformException.error(errMsg);
            }

            //流程表单个性化要素保存（设置关联的流程）
            flowableForm.setProcessId(createFlowResponse.getProcessId());

            //保存申请人部门信息
            PlatformUserDto userCreater = userService.getUsrUrls(flowableForm.getFlowCreateOperatorAccount());
            flowableForm.setFlowCreatorDepartment(userCreater.getDepartment());
            this.saveOrUpdateForm(devManageDto.getFlowableFormData(),operatorStart,createFlowResponse.getProcessId());

            //TODO 保存附件

            //提交事务
            transactionManager.commit(status);
        } catch (Exception e) {
            flowException = 1;
            logger.error("异常，", e);

            String errMsg = "产品终止流程创建出现异常，回滚当前事务，原因:" + e.getMessage();
            if (status != null) {
                logger.error(errMsg);
                transactionManager.rollback(status);
            }
            //flowable回滚
            if (Objects.nonNull(createFlowResponse) && Objects.nonNull(createFlowResponse.getProcessId())) {
                logger.error("流程删除:" + createFlowResponse.getProcessId());
                feignFlowableService.deleteProcess(ParamDeleteDto.builder().processIdList(Collections.singletonList(createFlowResponse.getProcessId())).build());
            }
            throw PlatformException.error(errMsg);
        } finally {
//            if (flowException==0){
//                notify(devManageDto.getFlowableFormData(),ImmutableList.of(flowableForm.getSystemAdminAccount()));
//            }
            if (flowException == 0 && CollectionUtil.isNotEmpty(taskAssignee.values()) && StrUtil.isBlank(devManageDto.getCreateToTaskDefinitionKey())){
                for(String accounts : taskAssignee.values()){
                    notify(devManageDto.getFlowableFormData(),Arrays.asList(accounts.split(",")));
                }
            }
        }

        return createFlowResponse;
    }

    private void saveOrUpdateForm(FlowFormDevManage flowableForm, String operatorStart, String processId) {
        //先删除已经入库的成员
        devMemberRepository.updateByProcessId(flowableForm.getProcessId(),DictConstant.DELETED);
        List<FlowFormDevMember> formDevMemberList = new ArrayList<>();
        //需求评审人员
        if (CollectionUtil.isNotEmpty(flowableForm.getDemandOkAccountList())){
            List<String> demanOkAccountList = flowableForm.getDemandOkAccountList();
            demanOkAccountList.forEach(e->{
                FlowFormDevMember m = new FlowFormDevMember();
                m.setMemberAccount(e);
                m.setMemberType(PlatformConstant.IT_DEV_MANAGE_MEMBER_DEMAND_OK);
                m.setMemberName(userCache.get(e).getName());
                m.setDeleted(DictConstant.NO_DELETE);
                formDevMemberList.add(m);
            });
        }
        //设计评审人员
        if (CollectionUtil.isNotEmpty(flowableForm.getDemandDesignAccountList())){
            List<String> demandDesignAccountList = flowableForm.getDemandDesignAccountList();
            demandDesignAccountList.forEach(e->{
                FlowFormDevMember m = new FlowFormDevMember();
                m.setMemberAccount(e);
                m.setMemberType(IT_DEV_MANAGE_MEMBER_DESIGN);
                m.setMemberName(userCache.get(e).getName());
                m.setDeleted(DictConstant.NO_DELETE);
                formDevMemberList.add(m);
            });
        }
        List<FlowFormTaskDetail> detailOrignal = new ArrayList<>();
        if (StrUtil.isNotEmpty(flowableForm.getProcessId())){
            FlowFormDevManage flowableFormOriginalDB =  devManageRepository.findByProcessId(flowableForm.getProcessId());
            if (flowableFormOriginalDB != null && CollectionUtil.isNotEmpty(flowableFormOriginalDB.getDetail())){
                flowableFormOriginalDB.getDetail().forEach(
                        e->{
                            FlowFormTaskDetail newDetail = new FlowFormTaskDetail();
                            BeanUtil.copyProperties(e,newDetail);
                            detailOrignal.add(newDetail);
                        }
                );
            }
        }
        devManageRepository.save(flowableForm);
        devMemberRepository.saveAll(formDevMemberList);
        PlatformUserDto createUser = userCache.get(operatorStart);
        DevTaskChangeLog log = new DevTaskChangeLog();
        log.setLogFlag(DictConstant.ADD);
        log.setRelateType(PlatformConstant.DEV_MANAGE_LOG_TYPE);
        log.setRelateId(processId);
        log.setLogJson(JSONObject.toJSONString(flowableForm));
        log.setOpOperator(operatorStart);
        log.setOpOperatorName(createUser.getName());
        devTaskChangeLogRepository.save(log);
        //判断任务状态有误变化
        if (StrUtil.isNotEmpty(flowableForm.getProcessId())){
            List<FlowFormTaskDetail> flowFormTaskDetails = flowableForm.getDetail();
            if (CollectionUtil.isNotEmpty(flowFormTaskDetails)){
                List<FlowFormTaskDetail> flowableFormOriginalDetail = detailOrignal;
                List<FlowFormTaskDetail> flowableFormOriginalDB = devTaskDetailRepository.findByProcessId(flowableForm.getProcessId());
                Map<Integer, FlowFormTaskDetail> taskMap = flowableFormOriginalDetail.stream()
                        .collect(Collectors.toMap(FlowFormTaskDetail::getTaskId, t -> t, ((key1, key2) -> key2)));
                for (int i = 0; i < flowFormTaskDetails.size(); i++) {
                    FlowFormTaskDetail task = flowFormTaskDetails.get(i);
                    if (task.getTaskId() == null){
//                        throw new IllegalArgumentException("task未保存");
                        DevTaskChangeLog taskLog = new DevTaskChangeLog();
                        taskLog.setLogFlag(DictConstant.ADD);
                        taskLog.setRelateType(PlatformConstant.TASK_MANAGE_LOG_TYPE);
                        taskLog.setRelateId(flowableFormOriginalDB.get(i).getTaskId().toString());
                        taskLog.setLogJson(JSONObject.toJSONString(task));
                        taskLog.setOpOperator(operatorStart);
                        taskLog.setOpOperatorName(createUser.getName());
                        taskLog.setStatus(task.getTaskState());
                        devTaskChangeLogRepository.save(taskLog);
                    } else {
                        if (taskMap.get(task.getTaskId()) == null){
                            DevTaskChangeLog taskLog = new DevTaskChangeLog();
                            taskLog.setLogFlag(DictConstant.ADD);
                            taskLog.setRelateType(PlatformConstant.TASK_MANAGE_LOG_TYPE);
                            taskLog.setRelateId(task.getTaskId().toString());
                            taskLog.setLogJson(JSONObject.toJSONString(task));
                            taskLog.setOpOperator(operatorStart);
                            taskLog.setOpOperatorName(createUser.getName());
                            taskLog.setStatus(task.getTaskState());
                            devTaskChangeLogRepository.save(taskLog);
                        } else {
                            FlowFormTaskDetail taskOld = taskMap.get(task.getTaskId());
                            if (!StrUtil.equals(task.getTaskState(),taskOld.getTaskState())){
                                DevTaskChangeLog taskLog = new DevTaskChangeLog();
                                taskLog.setLogFlag(DictConstant.ADD);
                                taskLog.setRelateType(PlatformConstant.TASK_MANAGE_LOG_TYPE);
                                taskLog.setRelateId(task.getTaskId().toString());
                                taskLog.setLogJson(JSONObject.toJSONString(task));
                                taskLog.setOpOperator(operatorStart);
                                taskLog.setOpOperatorName(createUser.getName());
                                taskLog.setStatus(task.getTaskState());
                                devTaskChangeLogRepository.save(taskLog);
                            }
                        }
                    }
                }
            }
        }
    }

    private Map<String, String> initTaskUserGroup(String operatorStart, DevManageDto devManageDto) {
        //流程节点，发起时动态指定节点处理人，
        Map<String, String> taskAssignee = new HashMap<>();
        taskAssignee.put("demandFirstGroup",devManageDto.getFlowableFormData().getSystemAdminAccount());
        PlatformUserDto staff = new PlatformUserDto();
        staff.setUsername(devManageDto.getFlowableFormData().getSystemAdminAccount());
        UserLeadersDto leader = userService.getDirectLeaderAndPrimaryDepartmentLeader(staff);
        if (leader.getAllLeaders().stream().anyMatch(e->e.equalsIgnoreCase(devManageDto.getFlowableFormData().getSystemAdminAccount()))){
            //如果系统管理员就是二级部门领导，则自己审批
            taskAssignee.put("innerLeaderGroup",devManageDto.getFlowableFormData().getSystemAdminAccount());
        } else {
            taskAssignee.put("innerLeaderGroup",leader.getDirectLeaders().stream().collect(Collectors.joining(",")));
        }
        return taskAssignee;
    }


    /**
     * 保存节点数据，但是不提交任务
     */
    public FlowDoTaskRespDto saveFormData(DevManageDto devManageDto, String operatorStart,boolean ignoreNode) {
        if (ObjectUtil.isNull(devManageDto)
                || ObjectUtil.isNull(devManageDto.getFlowableFormData())
                || StrUtil.isEmpty(operatorStart)) {
            throw PlatformException.errorWithOutMail("流程保存必填要素不能为空");
        }//TODO检查其它必填要素
//        检查已经创建gitee任务，但是第二次提交的时候gitee任务号没有刷新的情况
        FlowFormDevManage flowFormEvent = this.findFormByProcessId(devManageDto.getFlowableFormData().getProcessId());
        String config = systemConfigService.findConfigValueByCode("CONFIG_CHECK_GITEE_IDENT");
        if (flowFormEvent != null && StrUtil.isEmpty(config) ){
            //从传入对象取任务信息
            List<FlowFormTaskDetail> tasks = devManageDto.getFlowableFormData().getDetail();
            List<FlowFormTaskDetail> tasksDB = flowFormEvent.getDetail();
            for (FlowFormTaskDetail detail : tasks ) {
                if (StrUtil.isEmpty(detail.getGiteeIdent())){
                    //但是数据库中已经存在值
                    for (FlowFormTaskDetail detailDB : tasksDB ) {
                        if (detailDB.getTaskId() == detail.getTaskId()){
//                            Long count = detailDB.getDetailLog().stream().filter(e->e.getStatus().equals("已创建gitee任务")).count();
                            if (StrUtil.isNotEmpty(detailDB.getGiteeIdent())){
                                throw PlatformException.errorWithOutMail("任务状态有更新，请刷新页面后再提交");
                            }
                        }
                    }
                }
                if (StrUtil.isEmpty(detail.getGiteeDataBaseBranchStatus())){
                    //但是数据库中已经存在值
                    for (FlowFormTaskDetail detailDB : tasksDB) {
                        if (detailDB.getTaskId() == detail.getTaskId()){
//                            Long count = detailDB.getDetailLog().stream().filter(e->e.getStatus().equals("已创建gitee任务")).count();
                            if (StrUtil.isNotEmpty(detailDB.getGiteeDataBaseBranchStatus())){
                                throw PlatformException.errorWithOutMail("任务分支有更新，请刷新页面后再提交");
                            }
                        }
                    }
                }
            }
        }

        //保存节点不改变当前在哪个节点
        if (!ignoreNode){
            devManageDto.getFlowableFormData().setCurrentNodePassed(devManageDto.getTaskDefinitionKey());
        }

        FlowDoTaskRespDto respDto = null;
        if (StrUtil.isNotEmpty(devManageDto.getTaskId())) {//TODO 正式上线时，需要把taskId必传给打开
            respDto = flowCommonService.validCheckTaskBeforeSaveFormOrAuditTask(devManageDto.getTaskId());
        } else {
            respDto = new FlowDoTaskRespDto();
        }
        FlowFormDevManage flowableFormData = devManageDto.getFlowableFormData();
        if (StrUtil.isNotEmpty(respDto.getProcessId())) {
            flowableFormData.setProcessId(respDto.getProcessId());
        }
        this.saveOrUpdateForm(devManageDto.getFlowableFormData(),operatorStart,flowableFormData.getProcessId());

        return respDto;
    }


    /**
     * 审核通过
     */
    public FlowDoTaskRespDto taskAuditPass(DevManageDto devManageDto, String operatorAccount) {

        //【1.任务合法性数据】
        FlowDoTaskRespDto respDto = flowCommonService.validCheckTaskBeforeSaveFormOrAuditTask(devManageDto.getTaskId());
        //根据查询出的节点类型赋值
        devManageDto.setTaskDefinitionKey(respDto.getTaskDefinitionKey());

        //流程注入变量更新
        Map<String, String> taskAssignee = new HashMap<>();
        Map<String, String> conditionalVariable = new HashMap<>();

        //TODO 节点个性化处理
        if (PlatformConstant.IT_DEV_MANAGE_NODE_BEGIN_TASK.equals(devManageDto.getTaskDefinitionKey())) {//
            taskAssignee = this.initTaskUserGroup(operatorAccount, devManageDto);
            //保存流程部门，为系统负责人所在部门
            PlatformUserDto user = userService.getUsrUrls(devManageDto.getFlowableFormData().getSystemAdminAccount());
            devManageDto.getFlowableFormData().setSystemBelongDepartment(user.getDepartment());
        } else if ("innerLeaderTask".equals(devManageDto.getTaskDefinitionKey())) {//
            taskAssignee.put("demandFirstGroup",devManageDto.getFlowableFormData().getSystemAdminAccount());
        } else if (IT_DEV_MANAGE_NODE_DEMAND_FIRST_TASK.equals(devManageDto.getTaskDefinitionKey())) {
            if (devManageDto.getFlowableFormData().getDemandSetup().equals("0")){
                conditionalVariable.put("easy_task", "0");//进入立项，结束流程
            } else if (devManageDto.getFlowableFormData().getDemandSetup().equals("1")){
                conditionalVariable.put("easy_task", "1");//进入需求调研
                taskAssignee.put("demandAnalysisGroup",devManageDto.getFlowableFormData().getSystemAdminAccount());
            } else if (devManageDto.getFlowableFormData().getDemandSetup().equals("2")){
                conditionalVariable.put("easy_task", "2");//进入排期
                taskAssignee.put("taskArrangeGroup",devManageDto.getFlowableFormData().getSystemAdminAccount());
            } else {
                throw new IllegalArgumentException("是否立项值未匹配");
            }
             // 根据需要设置
        } else if (IT_DEV_MANAGE_NODE_DEMAND_ANALYSIS_TASK.equals(devManageDto.getTaskDefinitionKey())) {
            taskAssignee.put("okGroup",String.join(",", devManageDto.getFlowableFormData().getDemandOkAccountList()));
        } else if (IT_DEV_MANAGE_NODE_OK_TASK.equals(devManageDto.getTaskDefinitionKey())) {
            if (devManageDto.getFlowableFormData().getDemandNeedOaOk().equals("0")){
                conditionalVariable.put("need_ok", "0");//不需要进入OA合规评审
                taskAssignee.put("demandConfirmGroup",devManageDto.getFlowableFormData().getSystemAdminAccount());
            } else if (devManageDto.getFlowableFormData().getDemandNeedOaOk().equals("1")){
                conditionalVariable.put("need_ok", "1");//需要进入OA合规评审
                taskAssignee.put("OAOkGroup",devManageDto.getFlowableFormData().getSystemAdminAccount());
            } else {
                throw new IllegalArgumentException("是否进入OA合规评审值未匹配");
            }
        } else if (IT_DEV_MANAGE_NODE_OA_OK_TASK.equals(devManageDto.getTaskDefinitionKey())) {
            taskAssignee.put("recordOkGroup",devManageDto.getFlowableFormData().getSystemAdminAccount());// 分配OA评审发起任务处理者的逻辑
        } else if (IT_DEV_MANAGE_NODE_RECORD_OK_TASK.equals(devManageDto.getTaskDefinitionKey())) {
            // 分配记录OA评审任务处理者的逻辑
            if (devManageDto.getFlowableFormData().getDemandOaOkResult().equals("0")){
                conditionalVariable.put("is_ok", "0");//不合规
            } else if (devManageDto.getFlowableFormData().getDemandOaOkResult().equals("1")){
                conditionalVariable.put("is_ok", "1");//OA合规
                taskAssignee.put("demandConfirmGroup",devManageDto.getFlowableFormData().getSystemAdminAccount());
            } else {
                throw new IllegalArgumentException("OA合规值未匹配");
            }
        } else if (IT_DEV_MANAGE_NODE_DEMAND_CONFIRM_TASK.equals(devManageDto.getTaskDefinitionKey())) {
            taskAssignee.put("designGroup",String.join(",",devManageDto.getFlowableFormData().getDemandDesignAccountList()));// 分配需求确认任务处理者的逻辑
        } else if (IT_DEV_MANAGE_NODE_DESIGN_TASK.equals(devManageDto.getTaskDefinitionKey())) {
            taskAssignee.put("taskArrangeGroup",devManageDto.getFlowableFormData().getSystemAdminAccount());// 分配设计任务处理者的逻辑
        } else if (IT_DEV_MANAGE_NODE_TASK_ARRANGE_TASK.equals(devManageDto.getTaskDefinitionKey())) {
            if (CollectionUtil.isEmpty(devManageDto.getFlowableFormData().getDetail())){
                throw PlatformException.errorWithOutMail("任务不能空缺");
            }
            taskAssignee.put("testGroup",devManageDto.getFlowableFormData().getSystemAdminAccount());// 分配任务安排任务处理者的逻辑
        } else if (IT_DEV_MANAGE_NODE_TEST_TASK.equals(devManageDto.getTaskDefinitionKey())) {
            taskAssignee.put("waitOnlineGroup", PlatformLocalConstant.请启动关联上线流程);// 分配测试任务处理者的逻辑
        } else if (IT_DEV_MANAGE_NODE_WAIT_ONLINE_TASK.equals(devManageDto.getTaskDefinitionKey())) {
            taskAssignee.put("evalueGroup",devManageDto.getFlowableFormData().getFlowCreateOperatorAccount());// 分配上线任务处理者的逻辑
        } else if (IT_DEV_MANAGE_NODE_EVALUE_TASK.equals(devManageDto.getTaskDefinitionKey())) {
            devManageDto.getFlowableFormData().setIsClose(DictConstant.EVENT_NORMAL_CLOSE);
        } else {
            // 处理未知或错误的任务节点
            System.out.println("未知的任务节点: " + devManageDto.getTaskDefinitionKey());
            // 可以选择抛出异常或进行其他错误处理
        }
        String groupLeaderAccount = "";
        //审核事务通过
        TransactionStatus status = null;
        int flowException = 0;
        try {
            // 事务定义
            DefaultTransactionDefinition def = new DefaultTransactionDefinition();
            // 每次都开启一个新事务
            def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
            // 获取事务状态
            status = transactionManager.getTransaction(def);

            //保存表单数据
            FlowDoTaskRespDto saveRespDto = this.saveFormData(devManageDto, operatorAccount,false);
            if (saveRespDto == null) {
                throw PlatformException.error("保存表单数据失败");
            }
//            if (PlatformConstant.IT_DEV_MANAGE_NODE_BEGIN_TASK.equals(devManageDto.getTaskDefinitionKey())) {//
//
//
//            } else if (PlatformConstant.FLOW_EVENT_MANAGE_NODE_ANALYSIS.equals(devManageDto.getTaskDefinitionKey())) {//
//                //给节点处理人赋予处理人，如果当前人员是团队长，则跳过团队长审批节点
//                AppEhrResponse<LdapEhrDeptDto> depResp = iFeignLdapService.getDepByAccount(devManageDto.getFlowableFormData().getSystemAdminAccount());
//                if (Objects.isNull(depResp) || depResp.getStatus() != 0) {
//                    throw PlatformException.error("未找到部门信息");
//                }
//                LdapEhrDept depInfo = JSONObject.parseObject(JSONObject.toJSONString(depResp.getData()), LdapEhrDept.class);
//                groupLeaderAccount = depInfo.getLeader();
//                if (!"二级部门".equals(depInfo.getDepgrade()) || Strings.isBlank(depInfo.getLeader()) || depInfo.getLeader().equals(devManageDto.getFlowableFormData().getSystemAdminAccount())) {
//                    //特殊情况，团队长审批节点跳过
//                    conditionalVariable.put("hasLeaderTask",DictConstant.WORKFLOW_NODE_SKIP);
//                } else {
//                    conditionalVariable.put("hasLeaderTask",DictConstant.WORKFLOW_NODE_NO_SKIP);
//                    taskAssignee.put("leaderGroup",depInfo.getLeader());
//                }
//            } else if (PlatformConstant.FLOW_EVENT_MANAGE_NODE_AUDIT.equals(devManageDto.getTaskDefinitionKey())) {//
//                //关联整改id
//                //审核通过后创建改进流程
////                if (CollectionUtil.isNotEmpty(devManageDto.getFlowableFormData().getDetailImproves())) {
////                    for (FlowFormEventDetailImproveDto improveItem : devManageDto.getFlowableFormData().getDetailImproves()) {
////
////                        //获取整改负责人姓名
////                        String improvePersonList = improveItem.getImprovePersonList();
////                        String improvePersonNameList = "";
////                        if (StrUtil.isNotEmpty(improvePersonList)) {
////                            String[] personAccounts = improvePersonList.split(",");
////                            for (String person : personAccounts) {
////                                PlatformUserDto user = userCache.get(person);
////                                if (user == null) {
////                                    user = userService.saveUserByUserName(person);
////                                }
////                                if (user != null) {
////                                    improvePersonNameList = improvePersonNameList + user.getName() + ",";
////                                }
////                            }
////                            if (improvePersonNameList.length() > 1) {
////                                improvePersonNameList = improvePersonNameList.substring(0, improvePersonNameList.length() - 1);
////                            }
////                        }
////
////                        EventImproveTaskDto eventImproveTaskDto = new EventImproveTaskDto();
////                        FlowFormEventImproveDto formData = new FlowFormEventImproveDto();
////                        BeanUtil.copyProperties(improveItem, formData);
////                        formData.setProcessTitle(improveItem.getImproveTitle() + "-事件整改流程-" + improvePersonNameList + "-" + getCurrentDate(formatDate));
////                        formData.setFromImproveId(improveItem.getImproveId());
////                        formData.setFlowCreateOperatorAccount("系统自动创建");
////                        formData.setFlowCreateOperatorName("系统自动创建");
////                        formData.setFromEventProcessId(devManageDto.getFlowableFormData().getProcessId());
////                        formData.setFromEventProcessTitle(devManageDto.getFlowableFormData().getProcessTitle());
////                        eventImproveTaskDto.setFlowableFormData(formData);
////                        FlowDoTaskRespDto respCreate = eventImproveService.createFlow(eventImproveTaskDto, "admin");
////                        improveItem.setImproveProcessId(respCreate.getProcessId());
////                    }
////                    saveRespDto = this.saveFormData(devManageDto, operatorAccount);
////                    if (saveRespDto == null) {
////                        throw PlatformException.error("保存表单数据失败");
////                    }
////                }
//
//            } else if (PlatformConstant.FLOW_EVENT_MANAGE_NODE_TRACE.equals(devManageDto.getTaskDefinitionKey())) {//
//
//
//            }

            //审核流程通过，组织表单内容、审核注入变量、评论等
            //由负责人发起集成测试
//            if (IT_DEV_MANAGE_NODE_TEST_TASK.equals(devManageDto.getTaskDefinitionKey())) {
//                //发起测试流程
//                TestTaskFormDto testTaskFormDto = new TestTaskFormDto();
//                FlowFormTestTaskDto testFlowableFormData = new FlowFormTestTaskDto();
//                testFlowableFormData.setProcessTitle("【测试需求："+devManageDto.getFlowableFormData().getProcessTitle()+"】-系统创建-"+ LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")));
//                testFlowableFormData.setRequirementId(devManageDto.getProcessId());
//                testFlowableFormData.setRequirementTitle(devManageDto.getFlowableFormData().getProcessTitle());
//                testFlowableFormData.setFlowCreateOperatorName("系统自动创建");
//                testFlowableFormData.setFlowCreateOperatorAccount("系统自动创建");
//                testFlowableFormData.setSystemManager(devManageDto.getFlowableFormData().getSystemAdminAccount());
//                testFlowableFormData.setRequirementManager(devManageDto.getFlowableFormData().getDemandRelateAccount());
//                testTaskFormDto.setFlowableFormData(testFlowableFormData);
//                testTaskService.createFlow(testTaskFormDto, operatorAccount);
//            }

            ParamDoTaskDto paramDotaskDto = new ParamDoTaskDto();
            paramDotaskDto.setSysid(PlatformConstant.SYS_ID_GATEWAY);
            paramDotaskDto.setTaskId(devManageDto.getTaskId());
            paramDotaskDto.setComment(flowCommonService.initCommentDto(devManageDto.getCommentDto()));
            paramDotaskDto.setTitle("");
            paramDotaskDto.setContent(JsonTool.objectToJson(paramDotaskDto));//flowable网关保存每次审批的全量数据
            paramDotaskDto.setTaskAssignee(taskAssignee);
            paramDotaskDto.setConditionalVariable(conditionalVariable);
            paramDotaskDto.setComment(devManageDto.getCommentDto());


            //调用网关审核，注意前面表单的保存与这里审批通过，事物可能不一致，暂时不予处理这种不一致的情况
            FlowableResponse<ResponseMsgDto> flowableResponse = flowCommonService.taskAuditPass(paramDotaskDto);
            if (0 == flowableResponse.getStatus()) {
                //提交事务
                transactionManager.commit(status);

                return respDto;
            } else {
                String errMsg = "流程审核失败，错误码" + flowableResponse.getStatus() + "，原因：" + flowableResponse.getMsg() + "，详情：" + flowableResponse.getData();
                logger.error(errMsg);
                throw PlatformException.error(errMsg);
            }
        } catch (Exception e) {
            flowException = 1;
            if (status != null) {
                logger.error("事务事件流程创建出现异常，回滚当前事务");
                transactionManager.rollback(status);
            } else {
                logger.error("事务事件出现异常，transaction def status is null");
            }
            mailService.sendMailToAdminWithOutDB("需求管理流程审核异常", e.getMessage());
            throw e;
        } finally {
            //发送邮件和微信通知
            if (flowException == 0 && CollectionUtil.isNotEmpty(taskAssignee.values())){
                for(String accounts : taskAssignee.values()){
                    if (!StrUtil.equals(accounts,PlatformLocalConstant.请启动关联上线流程)){
                        notify(devManageDto.getFlowableFormData(),Arrays.asList(accounts.split(",")));
                    }
                }
            }

        }
    }

    public void notify(@NotNull FlowFormDevManage formDevManage, List<String> notifyAccount) {
        String[] mailList = userService.findAllByAccountList(notifyAccount).stream().map(User::getEmail).toArray(String[]::new);;
        SystemConfig agentIdConfig = systemConfigService.findByCode("WECHAT_GATEWAY_APP_AGENTID");
        boolean hasAgentIdConfig = Objects.nonNull(agentIdConfig) && Strings.isNotBlank(agentIdConfig.getConfigValue());
        //邮件通知
        String title = String.format("【需求流程】-【节点审核】-【%s】", formDevManage.getProcessTitle());
        String content = String.format("需求标题：%s<br/>  发起人：%s<br/>  需求系统：%s<br/>  负责人：%s<br/>  需求概要：%s<br/>  请知悉。可至国联技术服务平台内查阅相关事宜。"
                , formDevManage.getDemandTitle()
                , formDevManage.getFlowCreateOperatorName()
                , Optional.ofNullable(systemMainService.findBySystemClassNo(formDevManage.getSystemCode()))
                        .orElseThrow(() -> PlatformException.error("未找到系统：" + formDevManage.getSystemCode())).getOpName()
                , userCache.get(formDevManage.getSystemAdminAccount()).getName()
//                , (Objects.isNull(formDevManage.getEventGrade()) ? "无" :
//                        Optional.ofNullable(dictionaryService.findByDictEntryAndDictSubentry("event_manage_grade", formDevManage.getEventGrade()))
//                                .orElseThrow(() -> PlatformException.error("未找到字典项：event_manage_grade， " + formDevManage.getEventGrade())).getDictValue())
//                , (Objects.isNull(formDevManage.getEventClass()) ? "无" :
//                        Optional.ofNullable(dictionaryService.findByDictEntryAndDictSubentry("event_manage_class", formDevManage.getEventClass()))
//                                .orElseThrow(() -> PlatformException.error("未找到字典项：event_manage_class， " + formDevManage.getEventClass())).getDictValue())
                , formDevManage.getDemandSummary() != null && formDevManage.getDemandSummary().length() > 500 ? formDevManage.getDemandSummary().substring(0, 500) + "..." : formDevManage.getDemandSummary()
        );
        mailService.sendMail(mailList, null, title
                ,  DictConstant.TODO_LINK
                , title, content, null, Constant.MAIL_TYPE_IT_FLOW
        );
        if (hasAgentIdConfig) {
            iFeignShortmsgService.sendAgentMessageGeneric(MessageGenericVo.builder()
                    .oaUserAccounts(notifyAccount)
                    .agentId(agentIdConfig.getConfigValue())
                    .textContent("<br><a href='" + weChatUrl + "'>" + title + "</a>" +
                            "<br>  " + content)
                    .build());
        }
    }



    /**
     * 审核驳回
     */
    public FlowDoTaskRespDto taskAuditReject(DevManageDto taskDto, String operatorStart) {

        //【1.任务合法性数据】
        FlowDoTaskRespDto respDto = flowCommonService.validCheckTaskBeforeSaveFormOrAuditTask(taskDto.getTaskId());


        //【2.公共处理】检查文件必传性，zzp  TODO

        //【3.获取任务审核前的流程信息】
        ResponseSituationDto beforeAuditFlowInfo = flowCommonService.getProcessInfo(respDto.getProcessId());
        //END OF【公共处理】查询任务基础信息

        //各节点，驳回时，业务逻辑特殊处理

        ParamRollbackDto flowableTaskDto = new ParamRollbackDto();
        flowableTaskDto.setSysid(PlatformConstant.SYS_ID_GATEWAY);
        flowableTaskDto.setTaskId(taskDto.getTaskId());
        flowableTaskDto.setComment(flowCommonService.initCommentDto(taskDto.getCommentDto()).getFullMessage());
        flowableTaskDto.setTitle("XXXXX");
        flowableTaskDto.setContent(JsonTool.objectToJson(flowableTaskDto));
        //驳回时，要求提供title、comment
        flowableTaskDto.setComment(taskDto.getCommentDto().getFullMessage());

        FlowableResponse<FlowDoTaskRespDto> flowableResponse = flowCommonService.taskAuditReject(flowableTaskDto);
        if (0 == flowableResponse.getStatus()) {
            //流程回退成功,后续处理 TODO

            return flowableResponse.getData();
        } else {
            throw PlatformException.error("流程退回失败");
        }
    }

    /**
     * 根据流程实例ID或者任务ID检索流程
     *
     * @param taskDto processId 流程ID
     * @param taskDto taskId 任务ID
     */
    public DevManageDto getWorkFlowFormByTaskId(DevManageDto taskDto) {
        if (taskDto == null || StrUtil.isEmpty(taskDto.getTaskId()) && StrUtil.isEmpty(taskDto.getProcessId())) {
            throw PlatformException.error("查询产品终止流程时，需要提供流程实例Id或者任务Id和流程节点标识");
        }

        DevManageDto respDto = new DevManageDto();


        ResponseSituationDto currentTaskInfo = null;
        if (StrUtil.isEmpty(taskDto.getTaskId())) {//流程结束或者抄送查看流程时，仅根据processId检索要素信息
            respDto.setProcessId(taskDto.getProcessId());
            respDto.setHandleProcessMode(PlatformConstant.FLOWABLE_HANDLE_MODE_VIEW);
            respDto.setCurrentTaskInfo(new ResponseSituationDto());//减轻前段判空处理
        } else {
            taskDto.setTaskId(StrUtil.trim(taskDto.getTaskId()));
            respDto.setHandleProcessMode(PlatformConstant.FLOWABLE_HANDLE_MODE_EDIT);
            FlowableResponse<ResponseSituationDto> flowableTaskInfoResponse = flowCommonService.getTaskInfo(taskDto.getTaskId()
                    , PlatformConstant.SYS_ID_GATEWAY);
            if (flowableTaskInfoResponse.getStatus() != 0) {
                throw PlatformException.error("流程引擎未查询到任务信息" + taskDto.getTaskId());
            } else {
                taskDto.setProcessId(flowableTaskInfoResponse.getData().getProcessId());//后续保存策略会用到processId
                currentTaskInfo = flowableTaskInfoResponse.getData();
                respDto.setCurrentTaskInfo(currentTaskInfo);//task 任务详情
                respDto.setProcessId(currentTaskInfo.getProcessId());
                respDto.setTaskId(currentTaskInfo.getCurrentTaskId());//具体任务方式查看，需要taskId/taskDefinitionKey
                respDto.setTaskDefinitionKey(currentTaskInfo.getCurrentTaskDefinitionKey());
                respDto.setProcessDefineKey(currentTaskInfo.getProcessDefineKey());

                //加载任务节点信息
                ProcessEditConfigDto editConfigDto = processEditConfigService.getProcessEditConfigDto(respDto.getProcessDefineKey(), respDto.getTaskDefinitionKey());
                respDto.setProcessEditConfigDto(editConfigDto);
            }
        }

        //查询表单数据
        FlowFormDevManage flowFormEvent = this.findFormByProcessId(respDto.getProcessId());
        respDto.setFlowableFormData(flowFormEvent);

        return respDto;
    }



    public Page<ResponseSituationDevManageDto> getProcessSituationPage(Integer pageNo, Integer pageSize, FlowParamDevManageSearchDto paramSearchDto, String account) {
        LocalDateTime start = DateUtils.formatDateToLocalDateTime(DateUtils.formatDateString_(paramSearchDto.getBeginDate()));
        LocalDateTime end = DateUtils.formatDateToLocalDateTime(DateUtils.formatDateString_(paramSearchDto.getEndDate()));
        if (end != null) {
            end = end.plusDays(1);
        }

        paramSearchDto.setBeginDateLocalDate(start);
        paramSearchDto.setEndDateLocalDate(end);

        if (StrUtil.isNotEmpty(paramSearchDto.getSystemCode())) {
            paramSearchDto.setSystemCodes(Arrays.asList(paramSearchDto.getSystemCode().split(",")));
            paramSearchDto.setSystemCode(null);
        }

//        AppEhrResponse<List<LdapEhrDeptDto>> depts = iFeignLdapService.getAllDept();
//        List<LdapEhrDeptDto> deptinfoEntityList = Objects.nonNull(depts) && CollectionUtil.isNotEmpty(depts.getData()) ? depts.getData() : Collections.EMPTY_LIST;
//
//        if (paramSearchDto.getDeptId() != null) {
//            Map<Integer, LdapEhrDeptDto> deptMapDeptId = deptinfoEntityList.stream().collect(Collectors.toMap(LdapEhrDeptDto::getDepid, Function.identity(), (K1, K2) -> K2));
//            //如果是一级部门，需要获取其所有二级部门
//            LdapEhrDeptDto dept = deptMapDeptId.get(paramSearchDto.getDeptId());
//            if (dept.getDepgrade().equals(DictConstant.LEVEL_ONE_DEPARTMENT)) {
//                List<String> secondDepts = deptinfoEntityList.stream().filter(d -> d.getAdminid() != null && d.getAdminid().equals(dept.getDepid())).map(LdapEhrDeptDto::getDtitle).collect(Collectors.toList());
//                secondDepts.add(dept.getDtitle());
//                paramSearchDto.setDeptNames(secondDepts);
//            } else {
//                //二级部门
//                paramSearchDto.setDeptNames(ImmutableList.of(dept.getDtitle()));
//            }
//        }


        pageNo = PageUtil.initPageNo(pageNo);
        pageSize = PageUtil.initPageSize(pageSize);
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize);

        FlowParamAuthDto authCondition = new FlowParamAuthDto();
        //查询管理有多少人员，以查出人员在改善流程里的事件
        List<String> staffs = findAllByReportToCache(account);
        //分配给任务的人也可以看需求
        List<FlowFormTaskDetail> formTaskDetails = findAllByBeDeletedAndTaskPersonAccountCache(account);
        List<String> processIds = formTaskDetails.stream().map(e -> e.getProcessId()).collect(Collectors.toList());
        authCondition.setProcessIds(processIds);
        List<String> systemCodes = systemMemberService.querySystemCodeByMemberAccount(staffs);
        authCondition.setSystemCodes(systemCodes);
        //查询任务分配人的流程
        if (StrUtil.isNotEmpty(paramSearchDto.getTaskAccount())){
            List<FlowFormTaskDetail> taskDetails = devTaskDetailRepository.findAllByBeDeletedAndTaskPersonAccount(DictConstant.NO_DELETE,paramSearchDto.getTaskAccount());
            List<String> taskProcessIds = taskDetails.stream().map(e -> e.getProcessId()).distinct().collect(Collectors.toList());
            paramSearchDto.setTaskProcessId(taskProcessIds);
        }

        Page<FlowFormDevManage> result = null;
        if (!userService.userRoleContain(Constant.DEV_ADMIN, account)) {
            authCondition.setAdmin("0");
        }

        result = devManageRepository.searchByParam(pageable, paramSearchDto,authCondition,staffs);

//        result = flowEventUnionImporveRepo.searchByParam(pageable,paramSearchDto);
        List<FlowFormDevManage> content = result.getContent();
        List<ResponseSituationDevManageDto> process = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(content)) {
            for (FlowFormDevManage flow : content) {
                FlowableResponse<ResponseSituationDto> processInfo = feignFlowableService.getProcessInfo(flow.getProcessId());
                ResponseSituationDevManageDto dto = new ResponseSituationDevManageDto();
                BeanUtil.copyProperties(processInfo.getData(), dto);
                dto.setDemandGrade(flow.getDemandGrade());
                dto.setSystemCode(flow.getSystemCode());
                dto.setDemandSummary(flow.getDemandSummary());
                dto.setDemandClass(flow.getDemandClass());
                dto.setFlowCreateOperatorName(flow.getFlowCreateOperatorName());
                dto.setFlowCreateOperatorAccount(flow.getFlowCreateOperatorAccount());
                dto.setProcessCreateTime(flow.getProcessCreateTime());
                process.add(dto);
            }
        }

        Page<ResponseSituationDevManageDto> resultPage = new PageImpl(process, pageable, result.getTotalElements());
        return resultPage;
    }

    @Cacheable(cacheNames = "findAllByBeDeletedAndTaskPersonAccountCache#6000")
    private List<FlowFormTaskDetail> findAllByBeDeletedAndTaskPersonAccountCache(String account) {
        return devTaskDetailRepository.findAllByBeDeletedAndTaskPersonAccount(DictConstant.NO_DELETE,account);
    }

    @Cacheable(cacheNames = "findAllByReportToCache#6000")
    private List<String> findAllByReportToCache(String account) {
        List<VEhrAdminStaff> vEhrAdminStaffs = vEhrAdminStaffRepository.findAllByReportTo(account);
        return vEhrAdminStaffs.stream().map(VEhrAdminStaff::getAccount).collect(Collectors.toList());
    }


//    public byte[] export(FlowParamSearchDto paramSearchDto, String operatorStart) throws IOException {
//        paramSearchDto.setSystemCode(Strings.isNotBlank(paramSearchDto.getSystemCode()) ? paramSearchDto.getSystemCode() : null);
//        Page<ResponseSituationEventDto> page = this.getProcessSituationPage(paramSearchDto.getPageNo(), Integer.MAX_VALUE, paramSearchDto, operatorStart);
//        if (CollectionUtils.isEmpty(page.getContent())) {
//            throw PlatformException.error("未找到数据", false, false);
//        }
//        List<EventExportDto> datas = page.getContent().stream()
//                .map(s -> {
//                    EventExportDto dto = new EventExportDto();
//                    dto.setEventTitle(s.getProcessTitle());
//                    if (Strings.isNotBlank(s.getEventGrade())) {
//                        Optional.ofNullable(dictionaryService.findByDictEntryAndDictSubentry("event_manage_grade", s.getEventGrade()))
//                                .ifPresent(dict -> dto.setEventGrade(dict.getDictValue()));
//                    }
//                    //多条则合并为一个字符串，换行
//                    if (Objects.nonNull(s.getImproveCountAll()) && Integer.parseInt(s.getImproveCountAll()) > 0) {
//                        dto.setDetailImproves(
//                                eventImproveService.findAllByFromEventProcessId(s.getProcessId()).stream()
//                                        .map(improve -> improve.getProcessTitle() + (improve.getIsClose() == 1 ? "（已完成）" : "（未完成）"))
//                                        .collect(Collectors.joining("\r\n"))
//                        );
//                    }
//                    if (Strings.isNotBlank(s.getSystemCode())) {
//                        Optional.ofNullable(systemMainService.findBySystemClassNo(s.getSystemCode()))
//                                .ifPresent(sys -> dto.setSystemName(sys.getOpName()));
//                    }
//                    Optional.ofNullable(dictionaryService.findByDictEntryAndDictSubentry("event_cause", Objects.nonNull(s.getEventCause()) ? String.valueOf(s.getEventCause()) : "0"))
//                            .ifPresent(dict -> dto.setEventCause(dict.getDictValue()));
//                    if (Strings.isNotBlank(s.getEventClass())) {
//                        Optional.ofNullable(dictionaryService.findByDictEntryAndDictSubentry("event_manage_class", s.getEventClass()))
//                                .ifPresent(dict -> dto.setEventClass(dict.getDictValue()));
//                    }
//                    dto.setEventHappenTime(s.getEventHappenTime());
//                    dto.setFlowCreateOperatorName(s.getFlowCreateOperatorName());
//                    dto.setProcessCreateTime(s.getProcessCreateTime());
//                    return dto;
//                })
//                .collect(Collectors.toList());
//        return ReportFileUtil.export(datas, ReportFileConfigEnum.EVENT_FLOW);
//    }

    public void createGiteeDemandAndTask() {
        List<String> nodeNames = ImmutableList.of("任务排期","集成测试");
        List<FlowFormDevManage> result = devManageRepository.findAllByIsDeleteAndIsCloseAndCurrentNodeIn(DictConstant.NO_DELETE,NO_CLOSE,nodeNames);
        result = result.stream().filter(e->{
            //从来没同步过的需求
            if (StrUtil.isEmpty(e.getGiteeIssueId())){
                return true;
            }
            //同步过的需求，并有没同步过的任务的
            if (e.getDetail().stream().anyMatch(t->t.getGiteeTaskId()==null)){
                return true;
            }
            return false;
        }).collect(Collectors.toList());
        logger.info("需要同步的需求任务数量"+result.size());
        for(FlowFormDevManage devManage:result){
            try {
                Thread.sleep(100);
                giteeNewService.addGiteeDemand(devManage);
                giteeNewService.addGiteeTask(devManage);
            } catch (InterruptedException e){
                Thread.currentThread().interrupt();
                logger.error("创建git任务异常"+JSONObject.toJSONString(devManage),e);
                mailService.sendMailToAdmin("同步的需求失败",e.getMessage());
                devManage.setGiteeIssueId("-1");
                devManageRepository.save(devManage);
            } catch (Exception e){
                logger.error("创建git任务异常"+JSONObject.toJSONString(devManage),e);
                mailService.sendMailToAdmin("同步的需求异常",e.getMessage());
                devManage.setGiteeIssueId("-1");
                devManageRepository.save(devManage);
            }
        }
    }

    public void syncGiteeState() {
        List<String> nodeNames = ImmutableList.of("任务排期","集成测试");
        List<FlowFormDevManage> result = devManageRepository.findAllByIsDeleteAndIsCloseAndCurrentNodeIn(DictConstant.NO_DELETE,NO_CLOSE,nodeNames);
        result = result.stream().filter(e->StrUtil.isNotEmpty(e.getGiteeIssueId())).collect(Collectors.toList());
        logger.info("需要获取任务状态的数量"+result.size());
        for(FlowFormDevManage devManage:result){
            try {
                Thread.sleep(100);
                giteeNewService.syncGiteeState(devManage);
            } catch (InterruptedException e){
                Thread.currentThread().interrupt();
                logger.error("创建git任务异常"+JSONObject.toJSONString(devManage),e);
                mailService.sendMailToAdmin("创建git任务失败",e.getMessage());
            } catch (Exception e){
                logger.error("创建git任务异常"+JSONObject.toJSONString(devManage),e);
                mailService.sendMailToAdmin("创建git任务异常",e.getMessage());
            }
        }
    }

    public void syncGiteeBranch() {
        List<FlowFormTaskDetail> details = devTaskDetailRepository.findAllByBeDeletedAndGiteeIdentNotNullAndGiteeDataBaseIdNotNullAndGiteeDataBaseBranchStatusIsNull(DictConstant.NO_DELETE);
        for(FlowFormTaskDetail detail:details){
            try {
                Thread.sleep(100);
                if (StrUtil.equals("-1",detail.getGiteeIdent())){
                    continue;//出现过错误的忽略
                }
                giteeNewService.createBranch(detail);
            } catch (InterruptedException e){
                Thread.currentThread().interrupt();
                logger.error("创建git分支异常"+JSONObject.toJSONString(detail),e);
                mailService.sendMailToAdmin("创建git分支异常",e.getMessage());
                detail.setGiteeIdent("-1");
                devTaskDetailRepository.save(detail);
            } catch (Exception e){
                logger.error("创建git分支异常"+JSONObject.toJSONString(detail),e);
                mailService.sendMailToAdmin("创建git分支失败",e.getMessage());
                detail.setGiteeIdent("-1");
                devTaskDetailRepository.save(detail);
            }
        }
    }

    @Transactional
    public void syncDevManageCurrentNode() {
        try{
            List<FlowFormDevManage> contentNoClose = devManageRepository.findAllByIsDeleteAndIsClose(DictConstant.NO_DELETE,NO_CLOSE);
            List<FlowFormDevManage> contentClose = devManageRepository.findAllByCurrentNodeAndIsClose("等待上线",IS_CLOSE);
            List<FlowFormDevManage> content = new ArrayList<>();
            content.addAll(contentClose);
            content.addAll(contentNoClose);
            if (CollectionUtil.isNotEmpty(content)) {
                for (FlowFormDevManage flow : content) {
                    FlowableResponse<ResponseSituationDto> processInfo = feignFlowableService.getProcessInfo(flow.getProcessId());
                    String currentNode = processInfo.getData().getCurrentTaskName();
                    Integer status = parseInt(processInfo.getData().getStatus());
                    if (status == null){
                        devManageRepository.updateCurrentNode(currentNode,flow.getProcessId());
                    } else {
                        //单独更新，如果全部更新容易覆盖别处修改的数据,中途不能改content里的数据，否则也会保存。
                        devManageRepository.updateCurrentNodeAndIsClose(currentNode,status,flow.getProcessId());
                    }
                }
            }
        } catch (Exception e){
            logger.error("同步流程状态异常",e);
            mailService.sendMailToAdmin("同步流程状态异常",e.getMessage());
        }
    }

    public static Integer parseInt(String str) {
        try {
            return Integer.parseInt(str);
        } catch (NumberFormatException e) {
            return null;
        }
    }
}
